import { getType } from "./util";
import { getPrefixName } from "./toml"
import { useStorage,UseStorageOptions,StorageLike } from '@vueuse/core'
//
interface ILocalData {
  key: string;
  type: string;
  time: number;
  value: any;
}
// localstorage 保存数据
export const setStore = (key: string, value?: any) => {
  if (value == undefined) {
    localStorage.removeItem(key);
    return;
  }
  const data: ILocalData = {
    key,
    type: getType(value),
    time: new Date().getTime(),
    value,
  };
  localStorage.setItem(key, JSON.stringify(data));
};

// 获取 localstorage 保存的数据 type 可以用来对数据做初步类型转换 目前仅支持 json对象转换
export const getStore = (key: string, isDebug = false,time?:number) => {
  const data = localStorage.getItem(key);
  if (data == null) {
    return null;
  }
  try {
    const d:ILocalData = JSON.parse(data);
    if(isDebug === true){
      return d;
    }
    return d.value;
  } catch (e) {
    return data;
  }
}


export const saveLocal = (name:string,value:any) => {
  const key:string = getPrefixName(name)
  setStore(key,value)
}

export const getLocal = (name:string,isDebug?:boolean) => {
  const key:string = getPrefixName(name)
  return getStore(key,isDebug)
}

// 清空 localstorage
export const clearLocal = () => {
  localStorage.clear();
};

// 响应式的本地存储
/* 
 返回一个响应式对象,

*/
export const useLocal = (name:string,value:any,storage?:StorageLike,options?:UseStorageOptions<any>) => {
  const key:string = getPrefixName(name)
  return useStorage(key,value,storage,options)
}

